/**
 * 选择排序
 * 每次寻找剩余未排序的最小元素；
 * 将最小元素和当前元素交换
 */
public class SelectSort {

    /**
     * 交换数组下标为i
     * nums为i和j的值
     * @param nums
     * @param i
     * @param j
     */
    public void swap(int[] nums,int i,int j){
        if(nums.length<=0||i<0||j<0)
            return;
        if(i>nums.length||j>nums.length)
            throw new ArrayIndexOutOfBoundsException("数组越界");
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    /**
     * 在nums下标为begin开始处寻找最小值，并返回下标
     * @param nums
     * @param begin
     * @return
     */
    public int selectMinOfIndex(int[] nums,int begin){
        if(begin>=nums.length)
            throw new ArrayIndexOutOfBoundsException("数组越界");
        int min = nums[begin],min_of_index = begin;
        for (int i = begin+1; i < nums.length; i++) {
            if(min>nums[i]){
                min_of_index = i;
                min = nums[i];
            }
        }
        return min_of_index;
    }

    /**
     * 选择排序
     * @param nums
     */
    public void sort(int[] nums){
        if(nums.length<=0)
            return;
        int min_of_index = 0;
        for (int i = 0; i < nums.length; i++) {
            min_of_index = selectMinOfIndex(nums,i);
            swap(nums,i,min_of_index);
        }
    }

    public static void main(String[] args) {
        int[] nums = {2,1,6,3,10,4,-1,0,19,11,16,15,8};
        SelectSort selectSort = new SelectSort();
        selectSort.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i]+" ");
        }
    }
}
